<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    width="1000px"
    :visible.sync="visible">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="first">
        <el-form v-loading="formLoading" :model="dataForm" inline :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
          <el-form-item label="田块名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="田块名称"></el-input>
          </el-form-item>
          <el-form-item label="所属基地" prop="deptId">
              <el-input v-model="dataForm.deptName" v-popover:deptListPopover readonly="true" placeholder="所属基地"></el-input>
              <el-popover ref="deptListPopover" placement="bottom-start" trigger="click">
                <el-tree
                  ref="deptListTree" node-key="id" 
                  show-checkbox
                  :data="deptList" 
                  :props="deptListTreeProps"
                  @check-change="checkChange"
                  :check-strictly="true" 
                  :default-expand-all="true"
                  :highlight-current="true" 
                  :expand-on-click-node="false"
                >
                </el-tree>
            </el-popover>
          </el-form-item>
          <el-form-item label="农作物" prop="cropDict">
              <el-select v-model="dataForm.cropDict" class="form-item" filterable placeholder="请选择农作物">
                  <el-option
                  v-for="item in cropDictList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id">
                  </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="责任人" prop="handler" >
              <el-select 
                  class="form-item"
                  v-model="dataForm.handler"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键字"
                  :remote-method="remoteMethod"
                  :loading="handlerListLoading"
                  v-loadmore="handlerListLoadMore">
                  <el-option
                  v-for="item in handlerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                  </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="位置" prop="position">
            <el-input v-model="dataForm.position" placeholder="位置"></el-input>
          </el-form-item>
          <el-form-item label="农田状态" prop="status">
            <el-radio-group v-model="dataForm.status" class="form-item">
                <el-radio :label="0">荒废</el-radio>
                <el-radio :label="1">种植中</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="排序" prop="orderNum">
            <el-input-number class="form-item" v-model="dataForm.orderNum" controls-position="right" :min="0" placeholder="排序编号"></el-input-number>
          </el-form-item>
          </el-form>
      </el-tab-pane>
      <el-tab-pane v-if="dataForm.id" label="RTU信息" name="second">
        <bussrtuinfo ref="bussrtuinfo"></bussrtuinfo>
      </el-tab-pane>
      <el-tab-pane v-if="dataForm.id" label="设备信息" name="third">
        <bussrtuequipment ref="bussrtuequipment"></bussrtuequipment>
      </el-tab-pane>
      <el-tab-pane v-if="dataForm.id" label="巡检记录" name="fourth">
        <bussinspectiontask ref="bussinspectiontask"></bussinspectiontask>
      </el-tab-pane>
      <el-tab-pane v-if="dataForm.id" label="工单记录" name="five">
        <bussmaintaintask ref="bussmaintaintask"></bussmaintaintask>
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" v-loading="formLoading" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { treeDataTranslate } from '@/utils'
  import bussinspectiontask from './bussfarmlandinfo-input/bussinspectiontask'
  import bussmaintaintask from './bussfarmlandinfo-input/bussmaintaintask'
  import bussrtuequipment from './bussfarmlandinfo-input/bussrtuequipment'
  import bussrtuinfo from './bussfarmlandinfo-input/bussrtuinfo'
  export default {
    data () {
      return {
        visible: false,
        formLoading: false,
        dataForm: {
          id: 0,
          cropDict: '',
          handler: '',
          deptId: '',
          name: '',
          position: '',
          status: 0,
          orderNum: '',
          deptName: '',
        },
        activeName:'first',
        dataRule: {
          cropDict: [
            { required: true, message: '农作物不能为空', trigger: 'blur' }
          ],
          handler: [
            { required: true, message: '责任人不能为空', trigger: 'blur' }
          ],
          deptId: [
            { required: true, message: '所属基地不能为空', trigger: 'change' }
          ],
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '农田状态不能为空', trigger: 'blur' }
          ],
          orderNum: [
            { required: true, message: '排序编号不能为空', trigger: 'blur' }
          ]
        },
        deptList: [],// 部门列表
        deptListTreeProps: {
          label: 'name',
          children: 'children',
          disabled: function(data, node){
            return data.type == 1 ? false :true
          }
        },
        cropDictList:[],// 农作物列表
        handlerListLoading: false,
        handlerList:[],// 处理人列表
        hadlerParams:{}// 处理人查询参数
      }
    },
    components: {
      bussinspectiontask,
      bussmaintaintask,
      bussrtuequipment,
      bussrtuinfo
    },
    methods: {
      init (id) {
        this.activeName = 'first'

          // 加载负责人下拉框
        this.handlerListLoadMore('init')

        // 获取农作物字典列表
        this.$http({
          url: this.$http.adornUrl('/sys/dict/select'),
          method: 'get',
          params: this.$http.adornParams({
              "type": "crop_00"
          })
        }).then(({data}) => {
          this.cropDictList = treeDataTranslate(data.list, 'id')
        })

        // 初始化部门树
        this.$http({
          url: this.$http.adornUrl('/sys/dept/select2'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.deptList = treeDataTranslate(data.deptList, 'id')
        }).then(() => {
          this.dataForm.id = id || 0
          this.visible = true
          this.formLoading = false
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
            this.dataForm.deptName = ''

            if (this.dataForm.id) {
              this.$refs.bussinspectiontask.getDataList(this.dataForm.id)
              this.$refs.bussmaintaintask.getDataList(this.dataForm.id)
              this.$refs.bussrtuequipment.getDataList(this.dataForm.id)
              this.$refs.bussrtuinfo.getDataList(this.dataForm.id)

              this.$http({
                url: this.$http.adornUrl(`/buss/bussfarmlandinfo/info/${this.dataForm.id}`),
                method: 'get',
                params: this.$http.adornParams()
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.dataForm.cropDict = data.bussFarmlandInfo.cropDict
                  this.dataForm.handler = data.bussFarmlandInfo.handler
                  this.dataForm.deptId = data.bussFarmlandInfo.deptId
                  this.dataForm.name = data.bussFarmlandInfo.name
                  this.dataForm.position = data.bussFarmlandInfo.position
                  this.dataForm.status = data.bussFarmlandInfo.status
                  this.dataForm.orderNum = data.bussFarmlandInfo.orderNum
                  this.dataForm.version = data.bussFarmlandInfo.version
                  this.deptListTreeSetCurrentNode()
                }
              })
            }
          })
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid && !this.formLoading) {
            this.formLoading = true
            this.$http({
              url: this.$http.adornUrl(`/buss/bussfarmlandinfo/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'cropDict': this.dataForm.cropDict,
                'handler': this.dataForm.handler,
                'deptId': this.dataForm.deptId,
                'name': this.dataForm.name,
                'position': this.dataForm.position,
                'status': this.dataForm.status,
                'orderNum': this.dataForm.orderNum,
                'version': this.dataForm.version
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.formLoading = false
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 菜单树设置当前选中节点
      deptListTreeSetCurrentNode () {
        this.$refs.deptListTree.setChecked(this.dataForm.deptId,true,false)
        this.dataForm.deptName = (this.$refs.deptListTree.getCheckedNodes() || [])[0].name
      },
      // 节点修改
      checkChange(data, checked, node){
          if(checked == true){// 选中部门
              this.checkedId = data.id;
              this.$refs.deptListTree.setCheckedNodes([data])

              this.dataForm.deptId = data.id
              this.dataForm.deptName = data.name
          }
      },
      // 这里下拉框查询触发的方法
      remoteMethod(query) {
        this.handlerListLoadMore('query',query)
      },
      // 这里写入滚动加载要触发的方法
      handlerListLoadMore (type,query) {
        this.handlerListLoading = true

        if(type && (type == 'init' || type == 'query')){
            this.hadlerParams.page = 1
            this.handlerList = []
        }else if(this.hadlerParams.page){
            if(this.hadlerParams.page>=this.hadlerParams.totalPage){
                this.handlerListLoading = false
                return
            }
            this.hadlerParams.page += 1
        }
        
        var _this = this
        this.$http({
            url: this.$http.adornUrl('/sys/user/list2'),
            method: 'get',
            params: this.$http.adornParams({
                "name": query, //搜索参数
                "page": _this.hadlerParams.page || 1, //分页参数
                "limit": _this.hadlerParams.limit || 15, //每次查询15条记录
            })
        }).then(({data}) => {
            _this.handlerListLoading = false
            _this.hadlerParams.totalPage = data.page.totalPage
            _this.handlerList = _this.handlerList.concat(data.page.list)
        })
      }
    }
  }
</script>
<style scoped>
</style>
